package com.azure.code.dfs.island;

/**
 * https://leetcode.cn/problems/number-of-closed-islands/
 * 统计封闭岛屿的数目
 *  Numbers of Closed Islands
 * 和200题，求封闭岛屿， 将靠边的岛屿排除掉，剩下的 就是 封闭岛屿
 */
public class Island_1254 {

    int closeIsland(int[][] grid) {
        int m = grid.length, n = grid[0].length;

        for (int j = 0; j < n; j++) {
            // 把靠上边的岛屿淹没
            dfs(grid, 0, j);
            // 把靠下边的岛屿淹了
            dfs(grid, m - 1, j);
        }

        for (int i = 0; i < m; i++) {
            // 把左边的岛屿淹了
            dfs(grid, i, 0);
            // 把右边的岛屿淹了
            dfs(grid, i, n - 1);
        }
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0) {
                    res++;
                    dfs(grid, i, j);
                }
            }
        }
        return res;
    }

    // 从(i,j) 开始将岛屿变成海水
    private void dfs(int[][] grid, int i, int j) {
        int m = grid.length, n = grid[0].length;
        if (i < 0 || j < 0 || i >= m || j >= n) return;
        if (grid[i][j] == 1) return;
        grid[i][j] = 1;
        dfs(grid, i, j + 1);
        dfs(grid, i + 1, j);
        dfs(grid, i - 1, j);
        dfs(grid, i, j - 1);
    }
}
